package com.qf.limit.service.impl;

import cn.hutool.crypto.digest.MD5;
import cn.hutool.extra.pinyin.PinyinUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.limit.commons.exception.ServiceException;
import com.qf.limit.commons.r.Codes;
import com.qf.limit.dao.UserDao;
import com.qf.limit.entity.User;
import com.qf.limit.service.UserService;
import org.springframework.stereotype.Service;

/**
 * (User)表服务实现类
 *
 * @author makejava
 * @since 2024-09-10 09:34:37
 */
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {
    @Override
    public boolean save(User entity) {
        //密码加密
        //MD5 -> Hash算法（明文->MD5->32字符串形式）
        //password=123456
        //验证用户名是否存在
        User user = this.query().eq("username", entity.getUsername()).one();
        if (user != null) {
            //用户名已存在
            throw new ServiceException(Codes.USER_EXISTS);
        }

        entity.setPassword(MD5.create().digestHex(entity.getPassword()));
        //password=32字符串形式

        //昵称转拼音
        String pinyin = PinyinUtil.getPinyin(entity.getNikename()).replace(" ","");
        entity.setPinyin(pinyin);

        //entity ->1.password 2.多了一个pinyin
        return super.save(entity);
    }

    @Override
    public User queryUserName(String userName) {
        User user = this.query().eq("username", userName).one();
        return user;
    }
}
